package be.phl.mycinema.fragments;

import java.util.ArrayList;
import java.util.Collection;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import be.phl.mycinema.DetailActivity;
import be.phl.mycinema.R;
import be.phl.mycinema.Utils;
import be.phl.mycinema.adapters.MyListViewAdapter;
import be.phl.mycinema.classes.Film;
import be.phl.mycinema.classes.ReadJsonTask;

import com.google.gson.reflect.TypeToken;

public class AanbiedingFragment extends Fragment implements OnItemClickListener{

	private static final String TAG = "AANBIEDING FRAGMENT";
	private ArrayList<Film> films;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		View v =  inflater.inflate(R.layout.fragment_aanbiedingen,container, false);
		
		try {	
			if (Utils.isWebserviceAvailable()) {
				ListView myListview = (ListView) v.findViewById(R.id.list);
				
				ReadJsonTask<Film> a = new ReadJsonTask<Film>(getActivity(), TAG, new TypeToken<Collection<Film>>() {}.getType());

				films = a.execute(Utils.WEBSERVICE_BASE_ADDRESS + "/film/aanbiedingen").get();
				
				MyListViewAdapter adapter = new MyListViewAdapter(films,v.getContext());
				
				myListview.setAdapter(adapter);
				myListview.setOnItemClickListener(this);
			} else {
				Toast.makeText(getActivity().getBaseContext(), "De server is niet bereikbaar, probeer later opnieuw.", Toast.LENGTH_LONG).show();
				getActivity().finish();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}						
		return v;
	}
	
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {		
    	Intent i = new Intent(getActivity().getBaseContext(), DetailActivity.class);
    	i.putExtra("FILM", films.get(position));
    	startActivity(i);
	}
	
	@Override
	public void onDestroyView() {
		Log.d(TAG, "Aabiedingfragment destroyed.");
		super.onDestroyView();
	}
}
